﻿using JustTest.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.ModelBinding;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace JustTest.Author
{
    public partial class AuthorEditTest : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                var testId = this.Request.QueryString["id"];

                if (testId == null)
                {
                    this.Response.Redirect("~/Author/AuthorTests.aspx");
                    this.Response.End();
                    return;
                }

                //if (this.User.IsInRole("Author"))
                //{
                //    this.Response.Redirect("AuthorTests.aspx");
                //    this.Response.End();
                //    return;
                //}

                var db = new JustTestDb();
                if (!(db.Tests.Find(int.Parse(testId)).User.UserName == this.User.Identity.Name) &&
                    !(this.User.IsInRole("Admin")))
                {
                    this.Response.Redirect("~/Author/AuthorTests.aspx");
                    this.Response.End();
                    return;
                }
            }
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            var listView = this.TestEditFormView.FindControlRecursive("QuestionListView") as ListView;
            var pager = listView.FindControl("QuestionsDataPager") as DataPager;

            if (pager != null)
            {
                if (listView.Items.Count > 0)
                {
                    pager.Visible = true;
                }
                else
                {
                    pager.Visible = false;
                }
            }
        }

        public IQueryable<Category> CategoryDropDown_SelectItem()
        {
            var db = new JustTestDb();
            return db.Categoriess;
        }

        public JustTest.Models.Test TestEditFormView_GetItem([QueryString]int id)
        {
            var db = new JustTestDb();
            return db.Tests.Find(id);
        }

        public void QuestionCreateFormView_InsertItem()
        {
            var item = new JustTest.Models.Question();
            TryUpdateModel(item);
            var db = new JustTestDb();

            if (ModelState.IsValid)
            {
                item.Test = db.Tests.First(x => x.Id == (int)this.TestEditFormView.SelectedValue);

                db.Questions.Add(item);

                db.SaveChanges();

            }

           this.TestEditFormView.FindControl("QuestionListView").DataBind();
        }

        public IQueryable<JustTest.Models.Question> QuestionListView_GetData()
        {
            var db = new JustTestDb();

            return db.Tests.Find((int)this.TestEditFormView.SelectedValue).Questions.AsQueryable();
        }

        protected void QuestionLayoutCreateButton_Click(object sender, EventArgs e)
        {
            var listView = this.TestEditFormView.FindControl("QuestionListView") as ListView;
            listView.InsertItemPosition = InsertItemPosition.FirstItem;
            listView.FindControl("QuestionLayoutCreateButton").Visible = false;
        }

        protected void QuestionListView_ItemInserted(object sender, ListViewInsertedEventArgs e)
        {
            var listView = this.TestEditFormView.FindControl("QuestionListView") as ListView;
            listView.FindControl("QuestionLayoutCreateButton").Visible = true;
            listView.InsertItemPosition = InsertItemPosition.None;
        }

        protected void Unnamed_Click(object sender, EventArgs e)
        {
             var listView = this.TestEditFormView.FindControl("QuestionListView") as ListView;

             if (listView.Items.Count > 0)
             {
                 listView.FindControl("QuestionLayoutCreateButton").Visible = true;
                 listView.InsertItemPosition = InsertItemPosition.None;
             }
        }

        public void QuestionListView_UpdateItem(int id)
        {
            var db = new JustTestDb();
            JustTest.Models.Question item = db.Questions.Find(id);

            if (item == null)
            {
                ModelState.AddModelError("", String.Format("Item with id {0} was not found", id));
                return;
            }

            TryUpdateModel(item);

            if (ModelState.IsValid)
            {
                db.SaveChanges();

            }
        }

        public void QuestionListView_DeleteItem(int id)
        {
            var db = new JustTestDb();
            var question = db.Questions.Find(id);

            while(question.Answers.Count > 0)
            {
                db.Answers.Remove(question.Answers.First());
            }

            db.Questions.Remove(question);
            db.SaveChanges();

            this.TestEditFormView.FindControl("QuestionListView").DataBind();

            var listView = this.TestEditFormView.FindControl("QuestionListView") as ListView;

            if ((int)listView.DataKeys.Count <= 0)
            {
                listView.InsertItemPosition = InsertItemPosition.FirstItem;
                var btn = listView.FindControl("QuestionLayoutCreateButton");

                if (btn != null)
                {
                    btn.Visible = true;
                }
            }
        }

       
        public IQueryable<JustTest.Models.Answer> AnswersListView_GetData()
        {
            var listView = this.TestEditFormView.FindControl("QuestionListView") as ListView;
            var db = new JustTestDb();

            return db.Questions.Find((int)listView.DataKeys[listView.DataKeys.Count - 1].Value).Answers.AsQueryable();
        }

        public void AnswersListView_DeleteItem(int id)
        {
            var db = new JustTestDb();
            db.Answers.Remove(db.Answers.Find(id));
            db.SaveChanges();
        }

        public void AnswersListView_UpdateItem(int id)
        {
            var db = new JustTestDb();
            JustTest.Models.Answer item = db.Answers.Find(id);
            if (item == null)
            {
                ModelState.AddModelError("", String.Format("Item with id {0} was not found", id));
                return;
            }
            TryUpdateModel(item);
            if (ModelState.IsValid)
            {
                db.SaveChanges();

            }
        }

        public void AnswersListView_InsertItem()
        {
            var item = new JustTest.Models.Answer();
            TryUpdateModel(item);
           
            var db = new JustTestDb();
            var listView = this.TestEditFormView.FindControl("QuestionListView") as ListView;
            item.Question = db.Questions.Find((int)listView.DataKeys[0].Value);
            db.Answers.Add(item);
            db.SaveChanges();

        }

        protected void QuestionListView_DataBound(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                var listView = this.TestEditFormView.FindControl("QuestionListView") as ListView;

                if ((int)listView.DataKeys.Count <= 0)
                {
                    listView.InsertItemPosition = InsertItemPosition.FirstItem;
                    var btn = listView.FindControl("QuestionLayoutCreateButton");

                    if (btn != null)
                    {
                        btn.Visible = false;
                    }
                }
                else
                {
                    listView.InsertItemPosition = InsertItemPosition.None;
                    var btn = listView.FindControl("QuestionLayoutCreateButton");

                    if (btn != null)
                    {
                        btn.Visible = true;
                    }
                }
            }
        }

        // The id parameter name should match the DataKeyNames value set on the control
        public void TestEditFormView_UpdateItem(int id)
        {
            var db = new JustTestDb();
            var obj = db.Tests.FirstOrDefault(x => x.Id == id);

            JustTest.Models.Test item = obj;

            // Load the item here, e.g. item = MyDataLayer.Find(id);
            if (item == null)
            {
                // The item wasn't found
                ModelState.AddModelError("", String.Format("Item with id {0} was not found", id));
                return;
            }

            TryUpdateModel(item);

            if (ModelState.IsValid)
            {
                if (this.ViewState["testIsReleased"] != null)
                {
                    obj.Status = JustTest.Models.TestStatus.UnApproved;
                }

                db.SaveChanges();
            }


            this.Response.Redirect("~/Author/AuthorTests.aspx");
        }

        protected void TestEditFormView_ItemCommand(object sender, FormViewCommandEventArgs e)
        {
            if (e.CommandName == "Update" && e.CommandArgument.ToString() == "released")
            {
                this.ViewState["testIsReleased"] = true;
            }
        }

        protected void Unnamed_Click1(object sender, EventArgs e)
        {
            this.Response.Redirect("~/Author/AuthorTests.aspx");
            this.Response.End();
        }

       
    }
}